var initAroundSearch;
var aroundGraphicLayer;
var circleGraphicLayer;
var bufferCircle = null;
var draw;
var aroundSearchParam = [];
var setAroundParams;
var aroundSearchCenterGraphic;
var doNearQuery;
require([
    "dojo/on",
    "esri/symbols/SimpleLineSymbol",
    "esri/symbols/SimpleFillSymbol",
    "esri/symbols/PictureMarkerSymbol",
    "esri/layers/GraphicsLayer",
    "esri/graphic", "esri/Color",
    "esri/geometry/Point",
    "esri/geometry/Circle",
    "esri/InfoTemplate",
    "dojo/domReady!"
], function (
    on, SimpleLineSymbol, SimpleFillSymbol, PictureMarkerSymbol,
    GraphicsLayer, Graphic, Color, Point, Circle, InfoTemplate) {

    initAroundSearch = function () {
        circleGraphicLayer = new GraphicsLayer({
            id: "circleGraphicLayer"
        });
        map.addLayer(circleGraphicLayer);

        //反向地址搜索的图层
        aroundGraphicLayer = new GraphicsLayer({
            id: "aroundGraphicLayer"
        });

        aroundGraphicLayer.on("click", function (e) {

            if (map_click_handler) {
                //选中周边查询结果点后，先取消map的click事件，防止无法点击查询结果点
                map_click_handler.remove()
                //再次绑定map的click事件
                setTimeout(function () {
                    map_click_handler = map.on("click", function (e) {
                        const graphic = new Graphic(e.mapPoint)
                        initAroundSearchPanel()
                        doNearQuery(graphic)
                    })
                }, 100)
            }

        })
        map.addLayer(aroundGraphicLayer);
    }

    // const highlightPolySymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([2, 134, 255]), 2), new Color([125, 125, 125, 0.1]));
    // const highlightPolySymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([66, 186, 98]), 2), new Color([125, 125, 125, 0.1]));
    const highlightPolySymbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([23, 133, 52]), 3), new Color([125, 125, 125, 0.1]));

    var map_click_handler
    var aroundFlag = false
    $("#aroundBtn").click(function (e) {
        aroundFlag = !aroundFlag
        if (aroundFlag) {
            $(this).addClass("active")
            $("#aroundTipsPanel").show()
            map_click_handler = map.on("click", function (e) {
                const graphic = new Graphic(e.mapPoint)
                initAroundSearchPanel()
                doNearQuery(graphic)
                resetBtnPosition()
            })
        } else {
            $(this).removeClass("active")
            $("#aroundTipsPanel").hide()
            $("#aroundSearchBack").click()
            map_click_handler.remove()
        }
    })

    //tabs切换时，触发搜索
    $(".aroundSearchPanel_left_item").click(function (e) {
        $(this).addClass("active").siblings().removeClass("active");
        $(".el-tabs__active-bar").css("transform", `translateY(${this.offsetTop}px)`)
        // $("#aroundList .scrollbar").animate({
        //     scrollTop: 0
        // });
        $("#aroundList .scrollbar").scrollTop(0);
        doNearQuery(aroundSearchCenterGraphic, this.innerText)
    })

    //周边查询返回按钮，做清空相关内容处理
    $("#aroundSearchBack").click(function () {
        $(".aroundSearchPanel").hide();
        $("#aroundPage").empty();
        $("#aroundList ul").empty();
        $(".addressSearchPanel").show();

        $(".aroundSearchPanel_left_item:first").addClass("active").siblings().removeClass("active");
        $(".el-tabs__active-bar").css("transform", `translateY(0px)`)

        aroundGraphicLayer.clear();
        circleGraphicLayer.clear();
        addressGraphicLayer.show();
        map.infoWindow.hide();
        resetBtnPosition()

    });

    doNearQuery = function (graphic, type) {
        aroundSearchCenterGraphic = graphic
        const center = graphic.geometry
        type = type || "医疗卫生" //默认查询医疗卫生
        const bufferDistance = 3000;

        map.infoWindow.hide();
        aroundGraphicLayer.clear();
        circleGraphicLayer.clear();
        addressGraphicLayer.hide();

        $("#aroundList ul").empty();
        $("#aroundList .waitPanel").show();

        //绘制圆形查询范围及中心点
        const bufferCircle = new Circle({
            center: center,
            radius: bufferDistance
        });
        var circleGraphic = new Graphic(bufferCircle, highlightPolySymbol);
        circleGraphicLayer.add(circleGraphic);

        const pictureSymbol = new PictureMarkerSymbol("img/marker/map-marker.png", 30, 30).setOffset(0, 15);
        var pointGraphic = new Graphic(center, pictureSymbol, {}, graphic.infoTemplate);
        circleGraphicLayer.add(pointGraphic);

        map.centerAndZoom(center, 4);


        let aroundQueryList = []

        for (let key in aroundSearchData) {
            if (key === type) {
                const curTypeObj = aroundSearchData[key]
                for (let key in curTypeObj) {
                    const x1 = center.x;
                    const y1 = center.y;

                    let list = curTypeObj[key].filter(item => {
                        const x2 = item.x;
                        const y2 = item.y;
                        var xdiff = x2 - x1; // 计算两个点的横坐标之差
                        var ydiff = y2 - y1; // 计算两个点的纵坐标之差
                        const distance = Math.pow((xdiff * xdiff + ydiff * ydiff), 0.5);
                        item.DISTANCE = distance.toFixed(0)
                        item.TYPE = key
                        return distance <= bufferDistance
                    });

                    aroundQueryList.push(...list)
                }

                function sortBy(props) {
                    return function (a, b) {
                        return a[props] - b[props];
                    }
                }
                aroundQueryList.sort(sortBy("DISTANCE"));
            }
        }


        $("#aroundList .waitPanel").hide();
        $("#aroundPage").initPage(aroundQueryList.length, 1, buildAround);

        function buildAround(page) {
            if (aroundQueryList.length === 0) {
                $("#aroundList>ul").empty();
                var sli = "<li><span class='data_count'>未找到相关地点</span></li>"
                $("#aroundList>ul").append(sli);
                return
            }

            $("#aroundList>ul").empty();
            var sli = "<li><span class='data_count'>共有" + aroundQueryList.length + "个结果</span></li>"
            $("#aroundList>ul").append(sli);
            aroundGraphicLayer.clear();

            var max = page * 10;

            if (max > aroundQueryList.length) {
                max = aroundQueryList.length
            }

            let aroundGraphics = []

            for (let i = (page - 1) * 10; i < max; i++) {
                var item = aroundQueryList[i];

                var sms = new PictureMarkerSymbol("img/marker3/" + (i + 1 - (page - 1) * 10) + ".png", 33, 33).setOffset(0, 15);
                var pt = new Point(Number(item.x), Number(item.y), map.spatialReference);
                var attr = {};
                var infoCont = "<div class='infoCont'>";

                attr["名称"] = item.NAME;
                attr["类型"] = item.TYPE;
                attr["距离"] = item.DISTANCE;
                //   infoCont+="名称"+": "+ attr["名称"]+" <br/>";
                infoCont += "类型" + ": " + attr["类型"] + " <br/>";
                infoCont += "距离" + ": " + attr["距离"] + " 米 <br/>";
                infoCont += "</div>"

                var infoTemplate = new InfoTemplate("<b>" + attr["名称"] + "</b>", infoCont);
                var graphic = new Graphic(pt, sms, attr, infoTemplate);

                aroundGraphics.push(graphic)
                // aroundGraphicLayer.add(graphic);



                // //第一个地址显示infowindow
                // if (i === (page - 1) * 10) {
                //     map.infoWindow.hide();
                //     map.infoWindow.setContent(graphic.getContent());
                //     map.infoWindow.setTitle(graphic.getTitle());
                //     map.infoWindow.show(graphic.geometry);
                //     // map.centerAt(new Point(bufferCircle.center.x + 0.6 * bufferCircle.radius, bufferCircle.center.y + 0.12 * bufferCircle.radius, map.spatialReference));

                // }


                var li = document.createElement("li");
                var corp_name = document.createElement("p");
                corp_name.className = "corp_name";

                corp_name.innerHTML = "<img height='25px' src='img/marker3/" + (i + 1 - (page - 1) * 10) + ".png'/>" + "&nbsp" + attr["名称"];
                var person_name = document.createElement("p");
                person_name.className = "person_name";
                person_name.innerHTML = attr["类型"] + "<span style='float:right;margin-right:15px'>距离：" + attr["距离"] + "米</span>";

                li.appendChild(corp_name);
                li.appendChild(person_name);

                $("#aroundList>ul").append(li);

                (function (li, arg, idx, g) {
                    on(li, "click", function () {
                        $('#aroundList li').removeClass('activeli');
                        $(li).addClass('activeli');
                        // var center = newPoint(arg.x * 1 + 120, arg.y * 1, map.spatialReference);
                        // map.centerAndZoom(center, 6);
                        map.graphics.clear();

                        map.infoWindow.hide();
                        map.infoWindow.setContent(g.getContent());
                        map.infoWindow.setTitle(g.getTitle());
                        map.infoWindow.show(g.geometry);
                        // map.centerAndZoom(g.geometry, 6);

                    });
                })(li, pt, i, graphic);
            }

            async function showAroundGraphics(aroundGraphics) {
                for (const item of aroundGraphics) {
                    await addAroundGraphics(item)
                }
            }

            function addAroundGraphics(graphic) {
                return new Promise(function (resolve, reject) {
                    setTimeout(() => {
                        aroundGraphicLayer.add(graphic);
                        // aroundGraphicLayer.redraw();
                        resolve()
                    }, 30);
                });
            }

            showAroundGraphics(aroundGraphics)

        }

    }


})